let currentIndex = 0
let currentCount = 0
let totalCount = 0
let totalPreSecond = 0
let onceUpdate = 0
let oldUpdate = 0
let timer
let timeOut = 100
let emptyNum = 10

self.onmessage = function ({ data }) {
  let chartData = []
  let currentUpdate = onceUpdate
  switch (data.type) {
    case 'start':
      chartData = data.data
      totalCount = data.totalCount
      totalPreSecond = data.totalPreSecond
      onceUpdate = data.onceUpdate
      timeOut = data.timeOut
      oldUpdate = data.oldUpdate
      emptyNum = data.emptyNum
      for (let i = 0; i < data.totalCount; i++) {
        chartData.push(data.initNum)
      }
      self.postMessage({ type: 'start', data: chartData })
      clearInterval(timer)
      timer = setInterval(() => {
        setTimeout(() => {
          self.postMessage({
            type: 'interval'
          })
        }, 0)
      }, timeOut)
      break
    case 'interval-running':
      chartData = data.data
      currentUpdate =
        oldUpdate && oldUpdate !== 0
          ? currentCount % 2 === 0
            ? oldUpdate
            : onceUpdate
          : onceUpdate
      if (currentCount === 0 && data.currentData.length < totalPreSecond * 2) return
      if (currentCount === 0 && data.currentData.length > totalPreSecond * 2) {
        const shiftLength = data.currentData.length - totalPreSecond * 2
        currentCount++
        self.postMessage({ type: 'running-first', length: shiftLength }) // 将信息发送到主线程上
        console.log(data.currentData.length, 'running-first')
        return
      }
      if (data.currentData.length < currentUpdate) return
      // console.log(currentUpdate)
      currentCount++
      if (currentIndex === totalCount) {
        currentIndex = 0
      }
      for (let i = 0; i < currentUpdate; i++) {
        const val = data.currentData[i]
        chartData[currentIndex] = val === 0 || val === 65535 || val === 255 ? null : val
        currentIndex++
      }
      for (let i = 0; i < emptyNum; i++) {
        if (currentIndex + i === totalCount) {
          self.postMessage({
            type: 'running',
            data: chartData,
            length: currentUpdate
          }) // 将信息发送到主线程上
          return
        }
        chartData[currentIndex + i] = null
      }
      self.postMessage({ type: 'running', data: chartData, length: currentUpdate }) // 将信息发送到主线程上
      break
    case 'stop':
      clearInterval(timer)
      break
    default:
      break
  }
}
